package com.qef.com.mmovie.fragment.laugh_img;

import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.konifar.fab_transformation.FabTransformation;
import com.orhanobut.logger.Logger;
import com.qef.com.mmovie.App;
import com.qef.com.mmovie.R;
import com.qef.com.mmovie.api.NetApi;
import com.qef.com.mmovie.base.ActivityComponent;
import com.qef.com.mmovie.base.BaseActivity;
import com.qef.com.mmovie.base.BaseView;
import com.qef.com.mmovie.entity.LaughImgEntity;
import com.qef.com.mmovie.entity.User;
import com.qef.com.mmovie.entity.VVIdeoDetailsEntity;
import com.qef.com.mmovie.img.ImageLoader;
import com.qef.com.mmovie.mvp.adapter.CommentAdapter;
import com.qef.com.mmovie.presenter.LaughImgDetailsPresenter;
import com.qef.com.mmovie.presenter.contract.LauthImgDetailsContract;
import com.qef.com.mmovie.utils.AnimatiorUtils;
import com.qef.com.mmovie.utils.Constants;
import com.qef.com.mmovie.utils.DateUtil;
import com.qef.com.mmovie.utils.HindToolbar;
import com.qef.com.mmovie.utils.PopCreator;
import com.qef.com.mmovie.utils.PopWindowUtils;
import com.qef.com.mmovie.utils.ShareUtils;
import com.qef.com.mmovie.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

import static com.qef.com.mmovie.R.id.toolbar;

/**
 * Created by feq on 2017/4/8.
 */

public class LaughImgDetailFragment extends BaseActivity<LaughImgDetailsPresenter> implements Toolbar.OnMenuItemClickListener, LauthImgDetailsContract.View, View.OnClickListener {
    private BaseView dataBean;
    @BindView(R.id.img_detail)
    ImageView mImgDetail;
    @BindView(toolbar)
    Toolbar mToolbar;
    @BindView(R.id.bg_image)
    ImageView bgImage;
    @BindView(R.id.titlex)
    TextView title;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.description)
    TextView description;
    @BindView(R.id.fab)
    FloatingActionButton mFab;
    @BindView(R.id.videoplayer)
    JCVideoPlayerStandard mVideoPlayer;
    private RecyclerView rcCommon;
    private List<AVObject> commontDatas;
    private LinearLayout mViewx;
    VVIdeoDetailsEntity laughImgEntity;
    private String postid;
    private TextView mTvCommentCount;
    private int commentCount;

    //    @BindView(R.id.htext)
//    HTextView hTextView;
    //    public static LaughImgDetailFragment newInstance(LaughImgEntity.DataEntity dataBean) {
//        Bundle args = new Bundle();
//        args.putParcelable(ARG_ITEM, dataBean);
//        LaughImgDetailFragment fragment = new LaughImgDetailFragment();
//        fragment.setArguments(args);
//        return fragment;
//    }
    @Override
    protected int getLayoutId() {
        HindToolbar.setHintWindowTitle(getWindow());
        return R.layout.video_home_detail_fragment;
    }

    @Override
    protected void initEventAndData() {

        Bundle extras = getIntent().getExtras();
        Object dataBean = extras.get("dataBean");
        if (dataBean instanceof LaughImgEntity.DataEntity) {
            this.postid = ((LaughImgEntity.DataEntity) dataBean).getPostid();
//            LaughImgEntity.DataEntity dataBean1 = (LaughImgEntity.DataEntity) dataBean;
        } else {
            this.postid = ((VVIdeoDetailsEntity) dataBean).getData().getPostid();
//            VVIdeoDetailsEntity.DataBean dataBean1 = (VVIdeoDetailsEntity.DataBean) dataBean;
//            Logger.i(dataBean1.toString());
        }
        mPresenter.getLaughList(Integer.parseInt(postid));
    }

    @Override
    protected void initInject(ActivityComponent activityComponent) {
        activityComponent.inject(this);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.collect:
                if (User.isLoginToLogin(LaughImgDetailFragment.this)) {
                    NetApi.collection(laughImgEntity, new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            ToastUtil.showToast(App.getInstance(), "收藏成功！");
                        }
                    });
                }
                return true;
            case R.id.addx:
                ShareUtils.shareGirl(laughImgEntity.getData().getContent().getVideo().get(0).getTitle()
                        , laughImgEntity.getData().getContent().getVideo().get(0).getQiniu_url(), this);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    private void initView(VVIdeoDetailsEntity laughImgEntity) {
        mTvCommentCount = (TextView) findViewById(R.id.tv_comment_count);
        this.laughImgEntity = laughImgEntity;
        setViewAnimator();
        mViewx = (LinearLayout) findViewById(R.id.ll_comment);
        mFab.setBackgroundTintList(new ColorStateList(new int[][]{new int[0]}, new int[]{0xffffcc00}));
//
        mToolbar.setTitle("");
        initToolbarNav(mToolbar);
//
        ImageLoader.loadAll(this, laughImgEntity.getData().getContent().getVideo().get(0).getImage()
                , mImgDetail);
//        ImageLoader.loadAll(getActivity(), dataBean.getCover().getBlurred(), bgImage);
        title.setText(laughImgEntity.getData().getContent().getVideo().get(0).getTitle());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("#").append(laughImgEntity.getData().getCate())
                .append(" ")
                .append(" / ")
                .append(" ")
                .append(DateUtil.formatTime2(Integer.parseInt(
                        laughImgEntity.getData().getContent().getVideo().get(0).getDuration())));
        type.setText(stringBuilder.toString());
        description.setText(laughImgEntity.getData().getIntro());
//
        mFab.setOnClickListener(v -> {
            if (mFab.getVisibility() == View.VISIBLE) {
                FabTransformation.with(mFab).setListener(new FabTransformation.OnTransformListener() {
                    @Override
                    public void onStartTransform() {
                    }

                    @Override
                    public void onEndTransform() {
                        mVideoPlayer.setUp(laughImgEntity.getData().getContent().getVideo().get(0).getQiniu_url(),
                                JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
//                        mVideoPlayer.setUp(dataBean.getPlayUrl(), JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                        ImageView c = mVideoPlayer.thumbImageView;
                        ImageLoader.getInstance().displayLongImage(
                                laughImgEntity.getData().getContent().getVideo().get(0).getImage(),
                                App.getInstance(), c);
                        mVideoPlayer.setVisibility(View.VISIBLE);
                        mImgDetail.setVisibility(View.GONE);
                        mVideoPlayer.startVideo();
//                        JumpUtils.goToVideoPlayer(getActivity(), mImgDetail, dataBean);
                    }
                }).transformTo(mImgDetail);
            }
        });
        findViewById(R.id.bt_comment).setOnClickListener(this);
//
//        initColor();

    }

    private void setViewAnimator() {
        AnimatiorUtils.setTextViewAlphAnimator(description);
        AnimatiorUtils.setTextViewAlphAnimator(type);
        AnimatiorUtils.setTextViewAlphAnimator(title);

    }

    @Override
    public void showContent(VVIdeoDetailsEntity laughImgEntity) {
        initView(laughImgEntity);
        Logger.d("----------1111111111");
    }

    @Override
    public void error(Throwable throwable) {

    }

    protected void initToolbarNav(Toolbar toolbar) {
        toolbar.setNavigationIcon(R.mipmap.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
        toolbar.inflateMenu(R.menu.video_menu);
        toolbar.setOnMenuItemClickListener(this);
    }


    @Override
    public void onPause() {
        super.onPause();
        mVideoPlayer.release();

    }

    @Override
    public void onResume() {
        super.onResume();
        FabTransformation.with(mFab).setListener(new FabTransformation.OnTransformListener() {
            @Override
            public void onStartTransform() {
            }

            @Override
            public void onEndTransform() {
                if (mImgDetail.getVisibility() == View.INVISIBLE) {
                    mImgDetail.setVisibility(View.VISIBLE);
                }
            }
        }).transformFrom(mImgDetail);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_comment:
                actionComment();
                break;
        }
    }

    int color = 0xffffcc00;

    private void actionComment() {
        PopWindowUtils.with(this).loadLayout(R.layout.commentlayout).initPopWindow().setOnCustomListener(new PopCreator.PopCustomkListener() {
            CommentAdapter commAdapter;

            @Override
            public void onCustom(View view, PopupWindow popupWindow) {
                popupWindow.setOutsideTouchable(false);
                popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                rcCommon = (RecyclerView) view.findViewById(R.id.rc_comment);
                EditText commonEdit = (EditText) view.findViewById(R.id.common_edt);
                if (User.isLogin())
                    ImageLoader.getInstance().displayImage(App.getInstance(), User.getHead().toString(),
                            (ImageView) view.findViewById(R.id.iv_headx), 80, 80);
                view.setBackgroundColor(color);
                rcCommon.setBackgroundColor(color);
                commonEdit.setBackgroundColor(color);
                view.findViewById(R.id.iv_submit).setOnClickListener(view1 -> {
                    if (!User.isLoginToLogin(LaughImgDetailFragment.this)) {
                        popupWindow.dismiss();
                        openKeyboard();
                        return;
                    }
                    if (commonEdit.getText().toString().length() != 0) {
                        String content = commonEdit.getText().toString().trim();
                        NetApi.comment(Integer.parseInt(postid), content,
                                new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        mTvCommentCount.setText(String.valueOf(commentCount + 1));
                                        ToastUtil.showToast(App.getInstance(), "评论成功！");
                                        getCommentData();
                                        commonEdit.setText("");
                                        openKeyboard();
                                        //添加到我的评论接口
                                        NetApi.addMyCommentInfoX(laughImgEntity, content, Constants.Collection.VIDEO_3);
                                    }
                                });
                    } else {
                        ToastUtil.showToast(App.getInstance(), "评论内容不能为空！");
                    }
                });
                LinearLayoutManager layout = new LinearLayoutManager(App.getInstance(), LinearLayoutManager.VERTICAL, false);
                rcCommon.setLayoutManager(layout);
                commontDatas = new ArrayList<>();
                rcCommon.setAdapter(commAdapter = new CommentAdapter(App.getInstance(), commontDatas));
                getCommentData();
            }

            private void getCommentData() {
                commontDatas.clear();
                commAdapter.clear();
                NetApi.getComment(Integer.parseInt(postid), new FindCallback() {
                    @Override
                    public void done(List list, AVException e) {
                        Logger.i(list.toString());
                        commontDatas.addAll(list);
                        commAdapter.addAll(list);
                    }
                });
            }

        }).ShowAsDropDown(mViewx, 100, 0, 0);
    }

    /**
     * 软键盘隐藏，显示则隐藏 反正显示
     */
    private void openKeyboard() {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

}
